import 'dart:async';
import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:toast/toast.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  String phoneString = '';
  String codeString = '';
  bool loginEnable = false;

  @override
  void dispose() {
    // TODO: implement dispose
    codeTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ToastContext().init(context);
    return GestureDetector(
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Scaffold(
      backgroundColor: Color(0xFFF5F5F5),
      body: Stack(
        alignment: Alignment.topCenter,
        children: [
          Container(decoration: const BoxDecoration(image: DecorationImage(alignment:  Alignment.topCenter, image:  AssetImage('images/login_bg.png'), fit: BoxFit.contain,))),
          SafeArea(child: SingleChildScrollView(child: Column(
              children: [
                Align(
                  alignment: Alignment.centerRight, 
                  child: IconButton(icon: const Image(image: AssetImage('images/home_service_green.png'), width: 30, height: 30,), onPressed: (){ },),
                ),
          const SizedBox(height: 6),
          const Image(image: AssetImage('images/logo.png'), width: 62, height: 62,),
          const SizedBox(height: 6,),
          const Text('Bantuan Tunai', style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),),
          Container(
            margin: const EdgeInsets.only(left: 18, right: 18, top: 15),
            decoration: const BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(10)), 
                              color: Colors.white,
                              ),
            child:  Column(children: [
                      titleView1,
                      phoneView(),
                      const SizedBox(height: 20),
                      codeView(),
                      loginButton(),
                      privasiText
                    ],),
                    )
      ],),)
      ),
    ],),
   ),
    );
  }

  Widget titleView1 =  Container(
                        padding: const EdgeInsets.only(top: 8, bottom: 8),
                        color:const Color(0xFFFFF6E3),
                        width: double.infinity,
                        child: const Text('Gunakan nomor ponsel yang terkait dengan KTP \n Anda untuk mendaftar/login.', style: TextStyle(color: Color(0xFFCD842F), fontSize: 12), textAlign: TextAlign.center,),
                      );

  Widget phoneView() {
    return Container(
    margin: const EdgeInsets.only(left: 22, right: 22, top: 20),
    width: double.infinity,
    height: 46,
    decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(23)), border: Border.all(color: const Color(0xFFE5E5E5), width: 1)),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
      const SizedBox(width: 16),
     const Text('+52', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
     const SizedBox(width: 0),
      Expanded(child: TextField(
                        autocorrect: true,
                        maxLengthEnforcement: MaxLengthEnforcement.none,
                        decoration: const InputDecoration(
                                      hintText: 'Masukkan nomor telep', 
                                      hintStyle: TextStyle(color: Color(0xFFC2C2C2), fontSize: 12),
                                      border: OutlineInputBorder(borderSide: BorderSide.none),
                        ),
                      keyboardType: TextInputType.number,
                      inputFormatters: [LengthLimitingTextInputFormatter(10)],
                      onChanged: (value){
                        if (value.length == 10) { 
                          FocusScope.of(context).unfocus();
                         }
                        phoneString = value;
                        updateLoginButtonStatus();
                      },
                      ),
      ),
     const SizedBox(width: 16)
    ],),
  );
  }

  String codeButtonText = 'Kirim OTP';
  Timer? codeTimer;
  int codeTimerCount = 60;
  Widget codeView() {
    return Container(
    margin: const EdgeInsets.only(left: 22, right: 22),
    width: double.infinity,
    height: 46,
    decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(23)), border: Border.all(color: const Color(0xFFE5E5E5), width: 1)),
    child:  Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
      const SizedBox(width: 8),
       Expanded(child: TextField(
                        autocorrect: true,
                        maxLengthEnforcement: MaxLengthEnforcement.none,
                        decoration: const InputDecoration(
                                      hintText: 'Silakan masukkan kod', 
                                      hintStyle: TextStyle(color: Color(0xFFC2C2C2), fontSize: 12),
                                      border: OutlineInputBorder(borderSide: BorderSide.none),
                        ),
                      keyboardType: TextInputType.number,
                      inputFormatters: [LengthLimitingTextInputFormatter(4)],

                      onChanged: (value){
                        if (value.length == 4) { 
                          FocusScope.of(context).unfocus();
                         }
                        codeString = value;
                        updateLoginButtonStatus();
                      },
                      ),
      ),
      const SizedBox(width: 16),
      GestureDetector(
        onTap: () => {
          if (phoneString.isEmpty == true) {
            Toast.show('请先输入手机号码.', gravity: Toast.center)
          } else if (codeTimer == null || codeTimer?.isActive == false) {
            codeTimer = Timer.periodic(const Duration(seconds: 1), (timer) { 
              codeTimerCount --;    
              setState(() {
                if (codeTimerCount < 0) {
                  codeTimer?.cancel();
                  codeTimerCount = 60;
                  codeButtonText = 'Kirim OTP';
                } else {
                  codeButtonText = '$codeTimerCount''S';
                }
              });
            })
          } 
        },
        child: Container(
                alignment: Alignment.center,
                width: 78,
                height: double.infinity,
                decoration: BoxDecoration(
                                    borderRadius: const BorderRadius.only(topRight: Radius.circular(24), bottomRight: Radius.circular(24)),
                                    color: (codeTimer != null && codeTimer!.isActive == true) ? const Color(0xFFDEDEDE):const Color(0xFF21BC87),
                            ),
                child:  Text(codeButtonText, style: TextStyle(fontSize: 12, color: Colors.white),),
              ),
      ),
    ],),
  );
  }

  void updateLoginButtonStatus(){
    setState(() {
      if (phoneString.isEmpty == false && codeString.isEmpty == false) {
        loginEnable = true;
      } else {
        loginEnable = false;
      }
    });
  }

  Widget loginButton() {
    return GestureDetector(
    onTap: (){
      if (loginEnable == false ) { return; }
      
      Navigator.of(context).pop();
    },
    child: Container(
    alignment: Alignment.center,
    margin: const EdgeInsets.only(left: 22, right: 22, top: 54),
    width: double.infinity,
    height: 50,
    decoration: BoxDecoration(
      color: loginEnable ? Color(0xFF2EC685):Color(0xFFDEDEDE),
      borderRadius: BorderRadius.all(Radius.circular(25))
    ),
    child: const Text('Lanjut', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16),),
  ),
  );
  } 

  Widget privasiText = Container(
    margin: const EdgeInsets.only(left: 22, right: 22, top: 14, bottom: 22),
    width: double.infinity,
    child: RichText(
      textAlign: TextAlign.center,
      text: TextSpan(
            text: 'Dengan melanjutkan, Anda telah membaca dan menyetujui Kebijakan ',
            style: const TextStyle(color: Color(0xFFACACAC), fontSize: 12),
            children: <TextSpan>[
              TextSpan(
                text: 'Privasi kami',
                style: const TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF1EB989)),
                recognizer: TapGestureRecognizer()..onTap = () {
                  print('Privasi kami');
                },
                )
            ],
            ),
          ),
  );
}